package com.aero.cojbackendcommentservice.controller;

import com.aero.cojbackendcommentservice.service.ReplyService;
import com.aero.cojbackendmodel.model.dto.reply.ReplyAddRequest;
import com.aero.cojbackendmodel.model.dto.reply.ReplyEditRequest;
import com.aero.cojbackendmodel.model.dto.reply.ReplyQueryRequest;
import com.aero.cojbackendmodel.model.dto.reply.ReplyUpdateRequest;
import com.aero.cojbackendmodel.model.vo.ReplyVO;
import com.aero.cojbackendcommon.common.BaseResponse;
import com.aero.cojbackendcommon.common.DeleteRequest;
import com.aero.cojbackendcommon.common.ErrorCode;
import com.aero.cojbackendcommon.common.ResultUtils;
import com.aero.cojbackendcommon.exception.BusinessException;
import com.aero.cojbackendcommon.exception.ThrowUtils;
import com.aero.cojbackendmodel.model.entity.Reply;
import com.aero.cojbackendmodel.model.entity.User;
import com.aero.cojbackendserviceclient.service.UserFeignClient;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 评论接口
 *
 * @author Aero
 */
@RestController
@RequestMapping("/reply")
@Slf4j
public class ReplyController {

    @Resource
    private ReplyService replyService;

    @Resource
    private UserFeignClient userFeignClient;


    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param replyAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addReply(@RequestBody ReplyAddRequest replyAddRequest, HttpServletRequest request) {
        if (replyAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Reply reply = new Reply();
        BeanUtils.copyProperties(replyAddRequest, reply);
        replyService.validReply(reply, true);
        User loginUser = userFeignClient.getLoginUser(request);
        reply.setUserId(loginUser.getId());
        reply.setContent(replyAddRequest.getContent());
        reply.setQuestionId(replyAddRequest.getQuestionId());
        boolean result = replyService.save(reply);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newReplyId = reply.getId();
        return ResultUtils.success(newReplyId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteReply(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userFeignClient.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Reply oldReply = replyService.getById(id);
        ThrowUtils.throwIf(oldReply == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldReply.getUserId().equals(user.getId()) && !userFeignClient.isAdmin(user)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = replyService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param replyUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateReply(@RequestBody ReplyUpdateRequest replyUpdateRequest) {
        if (replyUpdateRequest == null || replyUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Reply reply = new Reply();
        BeanUtils.copyProperties(replyUpdateRequest, reply);
        // 参数校验
        replyService.validReply(reply, false);
        long id = replyUpdateRequest.getId();
        // 判断是否存在
        Reply oldReply = replyService.getById(id);
        ThrowUtils.throwIf(oldReply == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = replyService.updateById(reply);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Reply> getReplyById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Reply reply = replyService.getById(id);
        if (reply == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userFeignClient.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!reply.getUserId().equals(loginUser.getId()) && !userFeignClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(reply);
    }

    /**
     * 根据 id 获取（脱敏）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ReplyVO> getReplyVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Reply reply = replyService.getById(id);
        if (reply == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(replyService.getReplyVO(reply, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param replyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ReplyVO>> listReplyVOByPage(@RequestBody ReplyQueryRequest replyQueryRequest,
                                                         HttpServletRequest request) {
        long current = replyQueryRequest.getCurrent();
        long size = replyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Reply> replyPage = replyService.page(new Page<>(current, size),
                replyService.getQueryWrapper(replyQueryRequest));
        return ResultUtils.success(replyService.getReplyVOPage(replyPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param replyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ReplyVO>> listMyReplyVOByPage(@RequestBody ReplyQueryRequest replyQueryRequest,
                                                           HttpServletRequest request) {
        if (replyQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userFeignClient.getLoginUser(request);
        replyQueryRequest.setUserId(loginUser.getId());
        long current = replyQueryRequest.getCurrent();
        long size = replyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Reply> replyPage = replyService.page(new Page<>(current, size),
                replyService.getQueryWrapper(replyQueryRequest));
        return ResultUtils.success(replyService.getReplyVOPage(replyPage, request));
    }

    /**
     * 分页获取评论列表（仅管理员）
     *
     * @param replyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Reply>> listReplyByPage(@RequestBody ReplyQueryRequest replyQueryRequest,
                                                     HttpServletRequest request) {
        long current = replyQueryRequest.getCurrent();
        long size = replyQueryRequest.getPageSize();
        Page<Reply> replyPage = replyService.page(new Page<>(current, size),
                replyService.getQueryWrapper(replyQueryRequest));
        return ResultUtils.success(replyPage);
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param replyEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editReply(@RequestBody ReplyEditRequest replyEditRequest, HttpServletRequest request) {
        if (replyEditRequest == null || replyEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Reply reply = new Reply();
        BeanUtils.copyProperties(replyEditRequest, reply);
        // 参数校验
        replyService.validReply(reply, false);
        User loginUser = userFeignClient.getLoginUser(request);
        long id = replyEditRequest.getId();
        // 判断是否存在
        Reply oldReply = replyService.getById(id);
        ThrowUtils.throwIf(oldReply == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldReply.getUserId().equals(loginUser.getId()) && !userFeignClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = replyService.updateById(reply);
        return ResultUtils.success(result);
    }

}
